<?php

namespace app\admin\service;

use app\common\logic\CommonLogic;
use app\common\logic\OrderLogic;
use app\common\logic\SmsLogic;
use app\common\logic\WxAppLogic;
use app\common\model\commonModel;
use app\common\model\trAirportLine;
use app\common\model\trCar;
use app\common\model\trCarLine;
use app\common\model\trBusesLine;
use app\common\model\trOrder;
use app\common\model\trOrderOutletsDetail;
use app\common\model\trOutletsCar;
use app\common\model\trResource;
use app\common\model\trSystemSet;
use app\common\model\trUser;
use app\common\model\trVehicleLine;
use app\common\util\ErrorCode;

/**
 * Class Auth
 * @package app\admin\service
 * 订单服务类
 */
class OrderService
{
    private $data = [];
    private $params;
    private $returnData;
    private $mall_id = 0;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 获取订单数据的分页列表
    public function getList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            if(is_numeric($this->params["search"])){ //订单编号
                $filter[] = ['order_sn', '=', $this->params["search"]];
            }else{
                $userModel = new trUser();
                $filter[] = ['user_id', 'in', $userModel->getValue("id", [["nickname", "like", "%{$this->params["search"]}%"], ["mall_id", "=", $this->mall_id]])];
            }
        }
        if(!empty($this->params['type'])){
            $filter[] = ['type', '=', $this->params["type"]];
        }
        if(!empty($this->params['status'])){
            $filter[] = ['status', '=', $this->params["status"]];
        }
        if(!empty($this->params['timeFrom']) && !empty($this->params['timeTo'])){
            $filter[] = ['create_time', '<=', strtotime($this->params['timeTo'])];
            $filter[] = ['create_time', '>=', strtotime($this->params['timeFrom'])];
        }
        $field = "id,order_sn,address_from,address_to,contact_name,mobile,reserve_time,create_time,type,status,user_id";
        $model = new trOrder();
        $data = $model->getList($field, $filter, $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 订单的详细内容
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trOrder();
        $data = $model->getFields("*", ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(!empty($data)){
            $this->getDetailByType($data["type"], $data);
            if($data["type"] == "5"){ // 租车
                $data["reserveTime"] = str_replace(" ", " 至 ", $data["reserveTime"]);
                $detail = trOrderOutletsDetail::where("order_id", $data["id"])->find();
                $data["outletsServer"] = $detail->serve ? @json_decode($detail->serve, true) : [];
                $temp = trOutletsCar::alias("oc")->leftJoin(trCar::getTable()." c", "c.id=oc.car_id")
                    ->where(["oc.id" => $detail->oc_id])
                    ->field("c.model_number,c.appearance,c.icon,c.name,c.type")
                    ->find();
                $data["outletsData"] = [
                    "appearance" => $temp->appearance, "modelNumber" => $temp->model_number, "plateNumber" => $detail->plate_number,
                    "carIcon" => tome_dia(trResource::getValue("url", ["id" => $temp->icon])), "carName" => $temp->name,
                    "carType" => $temp->type == 1 ? "燃油" : ($temp->type == 2 ? "电动" : "混动"),
                ];
            }
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    public function getDetailByType($type, &$data){
        if($type == "1"){ //1机场接送，
            $model = new trAirportLine();
        }else if($type == "2"){ //2巴士路线，
            $model = new trBusesLine();
        }else if($type == "3"){ //3跨境专车接送
            $model = new trCarLine();
        }else if($type == "4"){ //4包车接送
            $model = new trVehicleLine();
        }else{
            return true;
        }
        $res = $model->getFields("car_type", ["id" => $data["lineId"], "mall_id" => $this->mall_id]);
        if(empty($res)){
            $data["carType"] = 0;
            $data["carTypeText"] = '';
        }else {
            $data["carType"] = $res["carType"];
            $data["carTypeText"] = $res["carTypeText"];
        }

        $data["allotData"] = ["carId" => $data["allotCarId"], "driverId" => $data["allotDriverId"], "notify" => $data["allotNotify"]];
        unset($data["allotCarId"], $data["allotDriverId"], $data["allotNotify"]);
        return true;
    }

    // 更新派单状态
    public function toUpdateAllot(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $this->data["status"] = 4;
        $model = new trOrder();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 更新派单数据
    public function toUpdateAllotData(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        if(empty($this->params['carId'])){
            return ErrorCode::code("params_not_exist", "carId");
        }
        if(empty($this->params['driverId'])){
            return ErrorCode::code("params_not_exist", "driverId");
        }
        $updateData = [
            "allot_car_id" => $this->params["carId"],
            "allot_driver_id" => $this->params["driverId"],
            "allot_notify" => isset($this->params["notify"]) ? $this->params["notify"] : "",
            "status" => 5, // 已分配
        ];
        $model = new trOrder();
        $result = $model->doUpdate($updateData, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }else{
            if(!empty($updateData["allot_notify"])) {
                $notify = explode(",", $updateData["allot_notify"]);
                $data = $model->getFields("user_id,order_sn,address_from,address_to,reserve_time,mobile,type,ride_number,allot_car_id,allot_driver_id,pay_money,memo", [
                    "id" => $this->params["id"], "status" => 5, "mall_id" => $this->mall_id
                ], true, false);
                $data["typeName"] = $model->getAttrByType($data["type"]);
                if (in_array("1", $notify)) { // 需要发短信
                    SmsLogic::orderAllocate($data); // 发送给用户
                    SmsLogic::orderAccept($data); // 发送给司机
                }
                if (in_array("2", $notify)) { // 发微信模板消息 - 司机端
                    $userModel = new trUser();
                    $userData = $userModel->alias("u")->rightJoin("driver d", "d.openid=u.openid")
                        ->where("d.id={$data["allotDriverId"]}")->field("u.id as driverId,d.openid")->find();
                    $data["driverId"] = $userData["driverId"];
                    WxAppLogic::sendOrderReceiptTpl($userData["openid"], $data);
                }
            }
        }
        return $this->returnData;
    }

    // 更新状态
    public function toUpdateStatus(){ //状态：3已取消；8已完成
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        if(!isset($this->params["status"])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [8,3])){
            return ErrorCode::code("params_error", "status(3已取消；8已完成)");
        }
        $this->data["status"] = $this->params["status"];

        $model = new trOrder();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 订单导出
    public function exportData(){
        $arr_header = ['ID', '订单号', '用户名', '用户电话', '上车点', '目的地', '下单时间', '出发时间', '订单类型', '订单状态'];
        $arr_width = ['8', '25', '15', '15', '60', '60', '20', '20', '12', '12'];
        $arr_key = ['id', 'orderSn', 'contactName', 'mobile', 'addressFrom', 'addressTo', 'createTime', 'reserveTime', 'typeName', 'statusText'];

        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            if(is_numeric($this->params["search"])){ //订单编号
                $filter[] = ['order_sn', '=', $this->params["search"]];
            }else{
                $userModel = new trUser();
                $filter[] = ['user_id', 'in', $userModel->getValue("id", [["nickname", "like", "{$this->params["search"]}%"], ["mall_id", "=", $this->mall_id]])];
            }
        }
        if(!empty($this->params['type']) && is_numeric($this->params["type"])){
            $filter[] = ['type', '=', $this->params["type"]];
        }
        if(!empty($this->params['status'])){
            $filter[] = ['status', '=', $this->params["status"]];
        }
        if(!empty($this->params['timeFrom']) && !empty($this->params['timeTo']) && strtotime($this->params['timeTo'])){
            $filter[] = ['create_time', '<=', strtotime($this->params['timeTo'])];
            $filter[] = ['create_time', '>=', strtotime($this->params['timeFrom'])];
        }
        $field = "id,order_sn,address_from,address_to,contact_name,mobile,reserve_time,create_time,type,status";
        $model = new trOrder();
        if(!empty($filter)) {
            $data = $model->getList($field, $filter, $page, $pageSize, "create_time desc", false);
        }else{
            $data = $model->getFields($field, $filter, false);
        }
        $res = CommonLogic::exportExcel(date("Y-m-d").'-订单数据导出', $arr_header, $arr_width, $arr_key, $data);
        if(is_array($res)) {
            $this->returnData["returnFile"] = $res;
            return $this->returnData;
        }
        return $this->returnData;
    }

    // 处理退款
    public function toHandleRefund(){ // status '状态：1待退款；2已退款；3已拒绝',
        if(empty($this->params['orderSn'])){
            return ErrorCode::code("params_not_exist", "订单编号");
        }
        if(empty($this->params['money'])){
            return ErrorCode::code("params_not_exist", "退款金额");
        }
        if(!isset($this->params['status'])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [2,3])){
            return ErrorCode::code("params_error", "status（2同意退款；3拒绝退款）");
        }
        $data = commonModel::getFields(refundTable, "id,order_sn", ['order_sn' => $this->params['orderSn'], "status" => 1, "mall_id" => $this->mall_id], true, false);
        if(empty($data)){
            return ErrorCode::code("params_not_exist", "申请退款记录不存在");
        }
        $update["status"] = $this->params["status"];
        $update["reason"] = isset($this->params["reason"]) ? $this->params["reason"] : '';
        if($this->params["status"] == "2"){ // 同意退款了
            $orderLogic = new OrderLogic();
            $result = $orderLogic->backRefundOrder($this->params["money"], $update, $data);
            if (isset($result["code"]) && $result["code"] != "0") {
                return $result;
            }
        }else {
            $result = commonModel::toUpdate(refundTable, $update, ['id' => $this->params['id'], "mall_id" => $this->mall_id]);
            if (isset($result["code"])) {
                return $result;
            }
            if($result) {
                $orderModel = new trOrder();
                $orderModel->doUpdate(["status" => 3, "reason" => $update["reason"]], ["order_sn" => $data["orderSn"], "mall_id" => $this->mall_id]);
            }
        }
        if(!$result) {
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "处理失败";
        }
        return $this->returnData;
    }

    // 订单设置
    public function orderSetting($type){
        if($type == "obtain"){ // 获取
            $cancelTime = trSystemSet::getValue("orderCancelTime");
            if(empty($cancelTime)){
                $cancelTime = 30; // 默认30分钟
            }
            $this->returnData["data"] = ["cancelTime" => $cancelTime];
        }elseif($type == "save"){ // 保存
            trSystemSet::toSave(isset($this->params["cancelTime"]) ? $this->params["cancelTime"] : 30, "orderCancelTime");
        }
        return $this->returnData;
    }

    // 订单提醒
    public function remindSetting($type){
        if($type == "obtain"){ // 获取
            $data = trSystemSet::getValue("orderRemindSetting");
            if(empty($data)){
                $data = [
                    "remind1" => ["status" => 0, "value" => ""], "remind2" => ["status" => 0, "value" => ""],
                    "remind3" => ["status" => 0, "value" => ""], "remind4" => ["status" => 0, "value" => ""],
                    "remind5" => ["status" => 0, "value" => ""],
                ];
            }else{
                foreach ($data as &$item){
                    $item["status"] = intval($item["status"]);
                }
            }
            $this->returnData["data"] = $data;
        }elseif($type == "save"){ // 保存
            for ($i = 1; $i <= 5; $i++) {
                $this->data["remind$i"] = [
                    "status" => isset($this->params["status$i"]) ? $this->params["status$i"] : 0,
                    "value" => isset($this->params["value$i"]) ? $this->params["value$i"] : "",
                ];
            }
            trSystemSet::toSave($this->data, "orderRemindSetting");
        }
        return $this->returnData;
    }

    // 删除订单
    public function toDel(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trOrder();
        $data = $model->getFields("status,trade_no", ["id" => $this->params['id'], "mall_id" => $this->mall_id], true, false);
        if(($data["status"] == "3" && empty($data["tradeNo"])) || $data["status"] == "9" || $data["status"] == "10") {
            $result = $model->delById($this->params['id']);
            if (isset($result["code"])) {
                return $result;
            }
            if (!$result) {
                $this->returnData = ErrorCode::$errorCode['fail'];
                $this->returnData["msg"] = "删除失败";
            }
        }else{
            $this->returnData = ErrorCode::$errorCode['fail'];
            $this->returnData["msg"] = "订单不能删除";
        }
        return $this->returnData;
    }
}